// src/pages/FundTrend/FundTrend.jsx

import React, { useLayoutEffect, useEffect, useRef, useState } from 'react';
import * as echarts from 'echarts';
import { Card, Spin, message, Input, Badge } from 'antd';
import { useSearchParams } from 'react-router-dom';
import { $fetchFundTrend } from '../../api/fundApi';
import {
  FundOutlined,
  SearchOutlined,
} from '@ant-design/icons';
import './FundTrend.scss';

const { Search } = Input;

const FundTrend = () => {
  // 1. 从 URL query string 里读取 symbol
  const [searchParams] = useSearchParams();
  const propSymbol = searchParams.get('symbol') || '';
  // 2. 内部状态：使用 propSymbol 初始化
  const [symbol, setSymbol] = useState(propSymbol);
  const [loading, setLoading] = useState(false);

  const chartRef = useRef(null);
  const chartInstance = useRef(null);

  // 3. 当 URL query 参数变化时，更新内部 symbol
  useEffect(() => {
    if (propSymbol && propSymbol !== symbol) {
      setSymbol(propSymbol);
    }
  }, [propSymbol]);

  // 4. 初始化 ECharts 实例（只执行一次）
  useLayoutEffect(() => {
    if (!chartRef.current) return;
    const container = chartRef.current;
    chartInstance.current = echarts.init(container);

    // 初始空白 Option
    chartInstance.current.setOption({
      title: {
        text: '请输入基金代码并点击“加载”',
        left: 'center',
        textStyle: { fontSize: 14, color: '#888' },
      },
      tooltip: { trigger: 'none' },
      xAxis: { type: 'category', data: [], axisLabel: { rotate: 45 } },
      yAxis: [{ type: 'value' }],
      series: [],
    });

    // 延迟再 resize 一次
    setTimeout(() => {
      chartInstance.current?.resize();
    }, 0);

    const handleResize = () => chartInstance.current?.resize();
    window.addEventListener('resize', handleResize);

    return () => {
      window.removeEventListener('resize', handleResize);
      chartInstance.current?.dispose();
      chartInstance.current = null;
    };
  }, []);

  // 5. 当 symbol 改变时，拉数据并绘图
  useEffect(() => {
    if (!symbol) return;
    const chart = chartInstance.current;
    if (!chart) return;

    const fetchData = async () => {
      setLoading(true);
      chart.resize();
      chart.showLoading({
        text: '数据加载中...',
        color: '#3399FF',
        textColor: '#333',
      });

      try {
        const rawData = await $fetchFundTrend(symbol);
        if (!Array.isArray(rawData) || rawData.length === 0) {
          throw new Error('后端返回数据为空或格式不对');
        }

        // 解析字段：“净值日期”、"单位净值"、"日增长率"
        const parsed = rawData.map((item) => {
          const dateGMT = item['净值日期'];
          const ts = new Date(dateGMT).getTime();
          return {
            ts,
            dateLabel: new Date(dateGMT).toISOString().slice(0, 10),
            netValue: parseFloat(item['单位净值']),
            dailyPct: parseFloat(item['日增长率']), // 已是百分比
          };
        });
        // 时间戳升序
        parsed.sort((a, b) => a.ts - b.ts);

        const dates = parsed.map((p) => p.dateLabel);
        const netValues = parsed.map((p) => p.netValue);
        const dailyPctArr = parsed.map((p) => p.dailyPct);

        chart.hideLoading();

        // 渐变填充：折线下方渐变
        const lineGradient = new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: 'rgba(24, 144, 255, 0.4)' },
          { offset: 1, color: 'rgba(24, 144, 255, 0.05)' },
        ]);

        // 构造 ECharts Option
        const finalOption = {
          title: {
            text: `${symbol} 基金净值趋势`,
            left: 'center',
            textStyle: { fontSize: 16 },
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: { type: 'cross' },
            formatter: (params) => {
              const nv = params.find((s) => s.seriesName === '单位净值');
              const dc = params.find((s) => s.seriesName === '日增长率');
              const date = nv ? nv.axisValueLabel : '';
              const nvVal = nv ? nv.data : '-';
              const dcVal = dc ? dc.data : '-';
              return (
                `${date}<br/>单位净值：${nvVal}<br/>日增长率：${dcVal}%`
              );
            },
          },
          legend: {
            top: 30,
            data: ['单位净值', '日增长率'],
          },
          xAxis: {
            type: 'category',
            data: dates,
            boundaryGap: false,
            axisLabel: { rotate: 45, fontSize: 12 },
          },
          yAxis: [
            {
              name: '单位净值',
              type: 'value',
              position: 'left',
              axisLabel: { formatter: '{value}' },
            },
            {
              name: '日增长率 (%)',
              type: 'value',
              position: 'right',
              offset: 60,
              axisLabel: { formatter: '{value} %' },
            },
          ],
          dataZoom: [
            { type: 'inside', xAxisIndex: 0 },
            { type: 'slider', xAxisIndex: 0 },
          ],
          series: [
            {
              name: '单位净值',
              type: 'line',
              data: netValues,
              yAxisIndex: 0,
              smooth: true,
              showSymbol: false,
              lineStyle: { width: 2, color: '#1890ff' },
              areaStyle: { color: lineGradient },
            },
            {
              name: '日增长率',
              type: 'bar',
              data: dailyPctArr,
              yAxisIndex: 1,
              barWidth: '60%',
              itemStyle: {
                color: '#36cfc9',
                opacity: 0.6,
              },
            },
          ],
        };

        chart.setOption(finalOption);
        // 再次强制 resize
        setTimeout(() => chart.resize(), 0);
      } catch (err) {
        console.error('[FundTrend] 拉取或绘制失败：', err);
        message.error(err.message || '获取基金走势失败');
        chart.hideLoading();
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, [symbol]);

  return (
    <div className="fund-trend-page">
      <div className="trend-header">
        <div className="header-content">
          <div className="header-title">
            <FundOutlined className="header-icon" />
            <h1>基金净值/涨幅可视化</h1>
            {symbol && <Badge count={symbol} className="symbol-badge" />}
          </div>
          <div className="search-wrapper">
            <Search
              placeholder="输入基金代码并点击“加载”"
              allowClear
              enterButton={<SearchOutlined />}
              onSearch={(val) => {
                const v = val.trim();
                if (!v) {
                  message.warning('请输入有效的基金代码');
                  return;
                }
                setSymbol(v);
              }}
              className="search-input"
              size="large"
            />
          </div>
        </div>
      </div>

      <Card className="trend-card" bordered={false}>
        <Spin spinning={loading} tip="加载中..." className="spin-center">
          <div ref={chartRef} className="chart-container" />
        </Spin>
      </Card>
    </div>
  );
};

export default FundTrend;
